﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.net.connecter.client;
using System.IO;
using FluorineFx.AMF3;
using FluorineFx;
using FluorineFx.IO;
using System.IO.Compression;
using System.Reflection;
using ServerSocket.com.net.connecter.model;

namespace ServerSocket.com.net.connecter.client
{
    public class Client :AbstractClient
    {
        private MemoryStream stream;

        private AMFReader reader;
        private BinaryWriter buffer;

        private long position=0;
        public Client()
        {
            stream = new MemoryStream();
            reader = new AMFReader(stream);
            buffer = new BinaryWriter(stream);
        }
        public override void Disconnected()
        {
            //throw new NotImplementedException();
        }

        public override void ReceiveData(byte[] bytes, int length)
        {
            Dictionary<string, object> o = null;
            stream.Position = stream.Length;
            buffer.Write(bytes, 0, length);

            while (true)
            {
                try
                {
                    stream.Position = position;
                    o =(Dictionary<string,object>) reader.ReadAMF3Data();

                    if (o.ContainsKey("c")==false)
                    {
                        return;
                    }
                    position = stream.Position;
                }
                catch (EndOfStreamException)
                {
                    //stream.Position = position;
                    return;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    //position = stream.Position;
                    return;
                }

                if (o !=null)
                {
                    Console.WriteLine(o);
                    CommandInfo cmd=new CommandInfo();
                    cmd.command="c";
                    cmd.data=new {a="hello"};
                    this.send(cmd);
                }
            }
        }

        public override void send(model.CommandInfo cmd)
        {
            ByteArray bytes = new ByteArray();
            bytes.WriteObject(cmd);

            this.Socket.Send(bytes.GetBuffer());
        }
    }
}
